<template>
  <div class="error-notebook-view">
    <el-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center">
          <span>我的错题本</span>
          <el-select
            v-model="selectedSubject"
            placeholder="请选择科目"
            size="small"
            style="width: 200px"
            @change="fetchErrorNotebook"
          >
            <el-option
              v-for="subject in subjectOptions"
              :key="subject"
              :label="subject"
              :value="subject"
            />
          </el-select>
        </div>
      </template>

      <el-table v-loading="loading" :data="errorList" stripe>
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="题目内容" prop="questionContent">
          <template #default="scope">
            <div v-html="md.render(scope.row.questionContent)"></div>
          </template>
        </el-table-column>
        <el-table-column label="错误次数" prop="errorCount" width="120" />
        <el-table-column label="最近错误时间" prop="lastErrorAt" width="200">
          <template #default="scope">{{
            new Date(scope.row.lastErrorAt).toLocaleString()
          }}</template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" type="primary" @click="getAIExplanation(scope.row.errorId)">
              AI 智能解析
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- AI 解析对话框 -->
    <el-dialog v-model="aiDialogVisible" title="AI 智能解析" width="60%">
      <div v-if="aiLoading" v-loading="aiLoading" style="height: 200px"></div>
      <div v-else class="ai-explanation" v-html="aiExplanation"></div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { apiClient, handleErrorAndRedirect } from '@/api'
import { ElMessage } from 'element-plus'
import MarkdownIt from 'markdown-it'
import mk from 'markdown-it-mathjax3'
import { AllSubjects } from '@/api/utils.ts'

const errorList = ref([])
const loading = ref(true)
const aiDialogVisible = ref(false)
const aiLoading = ref(false)
const aiExplanation = ref('')

const subjectOptions = AllSubjects
const selectedSubject = ref(subjectOptions[0])
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
}).use(mk)

const fetchErrorNotebook = async () => {
  loading.value = true
  try {
    const response = await apiClient.get('/student/me/error-notebook', {
      params: { subject: selectedSubject.value },
    })
    errorList.value = response.data
  } catch (error) {
    handleErrorAndRedirect(error, '获取错题本失败')
  } finally {
    loading.value = false
  }
}

const getAIExplanation = async (errorId: number) => {
  aiDialogVisible.value = true
  aiLoading.value = true
  aiExplanation.value = ''
  try {
    const response = await apiClient.get(`/ai/explanation/error/${errorId}`)
    let rawMarkdown = response.data.explanation || ''

    rawMarkdown = rawMarkdown.replace(/\$\s*([^$]+?)\s*\$/g, (_, content) => `$${content}$`)
    rawMarkdown = rawMarkdown.replace(/([^\$])\$\$+/g, '$1')
    rawMarkdown = wrapLatexBlock(rawMarkdown)

    aiExplanation.value = md.render(rawMarkdown)
  } catch (error) {
    ElMessage.error('获取AI解析失败')
    aiDialogVisible.value = false
  } finally {
    aiLoading.value = false
  }
}

function wrapLatexBlock(text: string): string {
  return text.replace(
    /^((?:\\\[|\\begin\{.+?\}|\\lim|\\int|\\frac|\\sum|\\left|\\right|\\sqrt)[^\n]*)$/gm,
    (match) => {
      return `$$\n${match}\n$$`
    },
  )
}

onMounted(fetchErrorNotebook)
</script>

<style scoped>
.error-notebook-view {
  padding: 20px;
}

.ai-explanation {
  line-height: 1.8;
}
</style>
